package 富婆梦.第一阶段.第五周.作业;

import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @ProjectName: java-learning
 * @Package: 富婆梦.第一阶段.第五周.作业
 * @ClassName: GetClassMessage
 * @Author: hemengjin
 * @Description: 获得对象信息的工具类
 * @Date:2021/8/21 21:36
 * @Version: 1.0
 */
public class GetClassMessage {
    public static void main(String[] args) {
        Person person = new Person();
        GetClassMessage getClassMessage = new GetClassMessage();
        //getClassMessage.getObjectName(person);
        getClassMessage.getObjectValue(person);
    }
    //输出对象名属性称的方法
    public void getObjectName(Object object){
        Class c = object.getClass();
        String className = c.getName();
        Field[] fields = c.getDeclaredFields();
        for (int i=0;i<fields.length;i++){
            System.out.print(fields[i].getGenericType()+" ");
            System.out.println(fields[i].getName());

        }
    }
    //输出对象属性值的方法
    public void getObjectValue(Object object){
        Class c = object.getClass();
        Field[] fields = c.getDeclaredFields();
        for (Field field:fields) {
            //将方法名称转成gett方法的驼峰格式
            String methodName = "get"+field.getName().substring(0,1).toUpperCase()+field.getName().substring(1);
            //System.out.println(methodName);
            try {
                Method m = c.getDeclaredMethod(methodName);
                Object value = m.invoke(object, new Object[]{});
                System.out.println("属性名为："+field.getName()+"，属性值是："+value);
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e){
                e.printStackTrace();
            }catch (IllegalAccessException e){
                e.printStackTrace();
            }
        }
    }
}
